package com.wangwenjun.concurrency.chapter14.blockingqueue;

import org.junit.Test;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * @Package: com.wangwenjun.concurrency.chapter14.blockingqueue
 * @ClassName: UseSynchronousQueue
 * @Author: lujieni
 * @Description:
 * @Date: 2021-03-11 11:31
 * @Version: 1.0
 *
 * SynchronousQueue
 * 1.容量为0
 * 2.
 *
 */
public class UseSynchronousQueue {

    public static void main(String[] args) {
        SynchronousQueue<String> blockingQueue = new SynchronousQueue<>();

        new Thread(()->{
            try {
                System.out.println(Thread.currentThread().getName()+" put 1");
                blockingQueue.put("1");
                System.out.println(Thread.currentThread().getName()+" put 2");
                blockingQueue.put("2");
                System.out.println(Thread.currentThread().getName()+" put 3");
                blockingQueue.put("3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"T1").start();


        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName()+":remove "+blockingQueue.remove());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName()+":remove "+blockingQueue.remove());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName()+":remove "+blockingQueue.remove());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"T2").start();
    }

    /**
     * java.lang.IllegalStateException: Queue full
     */
    @Test
    public void testAdd(){
        SynchronousQueue<String> blockingQueue = new SynchronousQueue<>();
        blockingQueue.add("a");
    }

    /**
     * false
     * offer的时候没有消费者在消费就是false
     */
    @Test
    public void testOffer(){
        SynchronousQueue<String> blockingQueue = new SynchronousQueue<>();
        System.out.println(blockingQueue.offer("a"));
    }

    /**
     * java.util.NoSuchElementException 没有元素直接抛错
     */
    @Test
    public void testRemove(){
        SynchronousQueue<String> blockingQueue = new SynchronousQueue<>();
        System.out.println(blockingQueue.remove());
    }

}